package gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.PrintStream;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import utils.JTextAreaOutputStream;

import opensslCore.ProcessHandler;

/*
 * @author Arnaud Sansig
 * @info Simple graphical openSSL interface
 */
public class IOpenSSL extends JFrame {
	private ProcessHandler process;			/*The working system*/
	private JTextAreaOutputStream error;
	private JTextAreaOutputStream stdout;
	private JTextField  tCmd;
	private JTextArea stderrArea;
	private JTextArea stdoutArea;
	
	/*
	 * @info Default constructor
	 * @info build the Frame and init params
	 */
	public IOpenSSL() {
		super("Interface graphique OpenSSL");
		
		/*Declarations*/
		JPanel pCenter=new JPanel();
		this.stdoutArea=new JTextArea();
		this.stderrArea=new JTextArea();
		this.error=new JTextAreaOutputStream(stderrArea);
		this.stdout=new JTextAreaOutputStream(stdoutArea);
		JScrollPane scrollErr=new JScrollPane(stderrArea);
		JScrollPane scrollStdout=new JScrollPane(stdoutArea);
		this.tCmd=new JTextField();
		
		/*Outputs stream*/
		System.setOut(new PrintStream(this.stdout, true));
		System.setErr(new PrintStream(this.error, true));
		
		/*Declarations*/
		this.process=new ProcessHandler();
		
		/*Init parameters*/
		this.setLayout(new BorderLayout());
		this.setSize(new Dimension(1024, 650));
		this.setVisible(true);
		this.setResizable(false);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		tCmd.setSize(new Dimension(800, 15));
		stderrArea.setEditable(false);
		stdoutArea.setEditable(false);
		pCenter.setLayout(new BoxLayout(pCenter, BoxLayout.Y_AXIS));
		
		/*Attach widgets to the current JFrame*/
		pCenter.add(scrollStdout);
		pCenter.add(scrollErr);
		this.getContentPane().add(pCenter, "Center");
		this.getContentPane().add(tCmd, "South");
		
		/*Listners*/
		tCmd.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				analyzeCmd(tCmd.getText());
				tCmd.setText("");
			}
		});
	}
	
	/*
	 * @info analyze a command 
	 * @param cmd the command
	 */
	private void analyzeCmd(String cmd) {
		if(cmd.equals("exit")) {
			this.process.close();
			this.dispose();
		}
		else if(cmd.equals("clear")) {
			this.stderrArea.setText("");
			this.stdoutArea.setText("");
		}
		else if(cmd.equals("show help")) {
			this.displayCmd();
		}
		else
		{
			process.writeOpenSSL(cmd);
		}
	}
	
	/*
	 * @info display the list of available commands
	 */
	private void displayCmd() {
		StringBuilder builder=new StringBuilder();
		builder.append("Liste des commandes disponibles : \n\n").append("clear\n").append("show help\n").append("exit\n");
		this.stdoutArea.setText(builder.toString());
	}
	
	public static void main(String args[]) {
		new IOpenSSL();
	}
}
